package admin.forms;

import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import admin.models.StaffModel;

import entities.Staff;

public class StaffForm {
	public static TreeMap checkValid(HttpServletRequest request, Staff user) {
		TreeMap form = new TreeMap();
		TreeMap check = new TreeMap();
		
		String username = (String) request.getParameter("username");
		String name = (String) request.getParameter("name");
		String status = (String) request.getParameter("status");
		String role = (String) request.getParameter("role");
		String action = (String) request.getAttribute("action");
		
		if ((username == null || username.equals(""))) {
			check.put("username", "Username is not empty");
			user.setUsername(username);
		} else {
			
			Pattern p = Pattern.compile("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
		    Matcher m = p.matcher(username);
		    if (!m.matches()) {
		    	check.put("username", "Username is not valid email.");
		    } else {
		    	StaffModel staffModel = StaffModel.getInstance();
				if ((action == null || !action.equalsIgnoreCase("edit")) && staffModel.checkUserExists(username)) {
					check.put("username", "Username has been exists! Please choose other username.");
				}
		    }
		    user.setUsername(username);
			
		}
		
		if (name == null || name.equals("")) {
			check.put("name", "Full name is not empty");
			user.setName("");
		} else {
			user.setName(name);
		}
		
		if (status != null) {
			try {
				user.setStatus(Integer.parseInt(status));
			} catch (Exception e) {
				check.put("status", "Status for user not valid!");
			}
		}
		
		if (role != null) {
			try {
				user.setRole(Integer.parseInt(role));
			} catch (Exception e) {
				check.put("role", "Role for user not valid!");
			}
		}
		
		form.put("checkValid", check);
		form.put("user", user);
		
		return form;
	}
}
